import React from 'react'
import { Menu, Layout, theme } from 'antd'
import type { MenuProps } from 'antd'
import { Link } from '@tanstack/react-router'
import { 
  HomeOutlined, 
  DashboardOutlined, 
  TeamOutlined, 
  SettingOutlined,
  InfoCircleOutlined,
  SearchOutlined
} from '@ant-design/icons'
import styles from './CustomSidebar.module.css'

const { Sider } = Layout

// 定义菜单项类型
interface MenuItem {
  key: string
  icon?: React.ReactNode
  label: React.ReactNode
  path?: string
  children?: MenuItem[]
}

export interface CustomSidebarProps {
  items: any[]
  selectedKeys: string[]
  collapsed?: boolean
  onCollapse?: (collapsed: boolean) => void
}

// 图标映射
const iconMap: Record<string, React.ReactNode> = {
  'HomeOutlined': <HomeOutlined />,
  'DashboardOutlined': <DashboardOutlined />,
  'TeamOutlined': <TeamOutlined />,
  'SettingOutlined': <SettingOutlined />,
  'InfoCircleOutlined': <InfoCircleOutlined />,
}

const CustomSidebar: React.FC<CustomSidebarProps> = ({ 
  items, 
  selectedKeys,
  collapsed = false,
  onCollapse
}) => {
  const { token } = theme.useToken()
  
  // 转换菜单项以包含图标和链接
  const convertItems = (items: any[]): MenuProps['items'] => {
    return items.map(item => {
      // 获取图标组件
      const icon = item.icon && typeof item.icon === 'string' 
        ? iconMap[item.icon] 
        : item.icon
        
      const convertedItem: any = {
        key: item.path || item.key,
        icon,
        label: item.path ? <Link to={item.path}>{item.label}</Link> : item.label
      }
      
      if (item.children) {
        convertedItem.children = convertItems(item.children)
      }
      
      return convertedItem
    })
  }
  
  const convertedItems = convertItems(items)

  return (
    <Sider 
      breakpoint="lg" 
      collapsedWidth="80" 
      width={220}
      collapsible
      collapsed={collapsed}
      onCollapse={onCollapse}
      style={{
        minHeight: '100vh',
        borderRight: `1px solid ${token.colorBorder}`,
        boxShadow: token.boxShadow,
        backgroundColor: token.colorBgContainer
      }}
      className={styles.sidebar}
      theme="light"
    >
      <div 
        style={{ 
          height: 64, 
          display: 'flex', 
          alignItems: 'center', 
          justifyContent: 'center',
          borderBottom: `1px solid ${token.colorBorder}`,
          color: token.colorText,
          fontSize: 18,
          fontWeight: 'bold',
          overflow: 'hidden',
          padding: '0 16px',
          backgroundColor: token.colorBgContainer
        }}
      >
        {collapsed ? 'AS' : 'Admin System'}
      </div>
      
      <Menu 
        theme="light"
        mode="inline"
        items={convertedItems}
        selectedKeys={selectedKeys}
        style={{ 
          border: 'none',
          background: 'transparent',
          color: token.colorText
        }}
        inlineIndent={16}
      />
    </Sider>
  )
}

export default CustomSidebar